package com.easyspringboot.bulider;

import com.easyspringboot.bean.Constants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;

/**
 * @Author xiaoyi
 * @Version 1.0
 * @ClassName BuildApplication
 * @Time 11:53
 */
public class BuildRunApplication {

    private static final Logger logger = LoggerFactory.getLogger(BuildController.class);

    public static void execute() {
        File folder = new File(Constants.PATH_RUNAPPLICATION);
        if (!folder.exists()) {
            folder.mkdirs();
        }
        File poFile = new File( folder,"RunApplication.java");
        OutputStream out = null;
        OutputStreamWriter outw = null;
        BufferedWriter bw = null;
        try {
            out = new FileOutputStream(poFile);
            outw = new OutputStreamWriter(out, "utf8");
            bw = new BufferedWriter(outw);
            bw.write("package " + Constants.PACKAGE_BASE + ";");
            bw.newLine();
            bw.newLine();
            bw.write("import org.mybatis.spring.annotation.MapperScan;");
            bw.newLine();
            bw.write("import org.springframework.boot.SpringApplication;");
            bw.newLine();
            bw.write("import org.springframework.boot.autoconfigure.SpringBootApplication;");
            bw.newLine();
            bw.newLine();
            //@SpringBootApplication
            //@MapperScan("com.mysqldemo.mappers")
            //public class RunApplicationDemo {
            //    public static void main(String[] args) {
            //        SpringApplication.run(RunApplicationDemo.class,args);
            //    }
            //}
            bw.write("@SpringBootApplication");
            bw.newLine();
            bw.write("@MapperScan(\""+Constants.PACKAGE_MAPPER+"\")");
            bw.newLine();
            bw.write("public class RunApplication {");
            bw.newLine();
            bw.write("    public static void main(String[] args) {");
            bw.newLine();
            bw.write("        SpringApplication.run(RunApplication.class,args);");
            bw.newLine();
            bw.write("    }");
            bw.newLine();
            bw.write("}");
            bw.newLine();
            bw.flush();

        } catch (Exception e) {
            logger.error("创建Mapper失败", e);
        } finally {
            if (bw != null) {
                try {
                    bw.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }
            if (outw != null) {
                try {
                    outw.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }

        }
    }

}
